package com.xuegao.xuegaololskills.swing;

import java.awt.*;
import java.awt.event.KeyEvent;
import java.util.concurrent.TimeUnit;

/**
 * <br/> @PackageName：com.xuegao.xuegaololskills.swing
 * <br/> @ClassName：IsKeyPressed
 * <br/> @Description：
 * <br/> @author：xuegao
 * <br/> @date：2020/11/15 12:47
 */
public class IsKeyPressed {
    private static volatile boolean wPressed = false;

    public static boolean isWPressed() {
        synchronized (IsKeyPressed.class) {
            return wPressed;
        }
    }

    public static void main(String[] args) {
        KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new KeyEventDispatcher() {
            @Override
            public boolean dispatchKeyEvent(KeyEvent ke) {
                System.out.println(" dispatchKeyEvent ");
                synchronized (IsKeyPressed.class) {
                    switch (ke.getID()) {
                        case KeyEvent.KEY_PRESSED:
                            if (ke.getKeyCode() == KeyEvent.VK_W) {
                                wPressed = true;
                            }
                            break;

                        case KeyEvent.KEY_RELEASED:
                            if (ke.getKeyCode() == KeyEvent.VK_W) {
                                wPressed = false;
                            }
                            break;
                    }
                    System.out.println("hfghg");
                    return false;
                }
            }
        });
        try {
            while (true) {
                if (IsKeyPressed.isWPressed()) {
                    System.out.println(" IsKeyPressed.isWPressed() ");
                    break;
                }
                TimeUnit.SECONDS.sleep(1);
                System.out.println(" no no no no ");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}